package com.wang.config.security;

import com.wang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author JoyBoy
 */
@Component
@Slf4j
public class AuthenticationHandler  implements UserDetailsService {

    @Resource
    private UserService userService;

    private final PasswordEncoder pw;


    @Autowired
    public AuthenticationHandler(PasswordEncoder pw) {
        this.pw = pw;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.wang.domain.User user = userService.getUserByUserName(username);

        if (user == null){
            throw new UsernameNotFoundException("username is null");
        }
        log.info("用户[{}]发送了登录请求", username);

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().getName()));

        return new User(user.getUserName(), pw.encode(user.getPassword()), grantedAuthorities);
    }
}


